package com.arox.springinaction.post;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service("frontDeskJms")
public class FrontDeskJmsImpl implements FrontDesk {
    
    @Value("${jms.brokerURL}")
    private String brokerURL;
    
    @Value("${jms.mail.queue}")
    private String queueName;

    public void sendMail(Mail mail) {
	ConnectionFactory cf = new ActiveMQConnectionFactory(brokerURL);
	Destination destination = new ActiveMQQueue(queueName);

	Connection conn = null;
	try {
	    conn = cf.createConnection();
	    Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
	    MessageProducer producer = session.createProducer(destination);
	    MapMessage message = session.createMapMessage();
	    message.setString("mailId", mail.getMailId());
	    message.setString("country", mail.getCountry());
	    message.setDouble("weight", mail.getWeight());
	    producer.send(message);
	    session.close();
	} catch (JMSException e) {
	    throw new RuntimeException(e);
	} finally {
	    if (conn != null) {
		try {
		    conn.close();
		} catch (JMSException e) {
		}
	    }
	}
    }

}
